package com.itheima.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/member")
public class MemberController {

    @Reference
    private MemberService memberService;


    @Autowired
    JedisPool jedisPool;

    @RequestMapping("/login")
    //用户登录
    public Result login(HttpServletResponse response, @RequestBody Map map){

        //1.获取用户填写的验证码
        String validateCode = (String) map.get("validateCode");
        //2.获取redis中存储的验证码
        String telephone = (String) map.get("telephone");
        String validateCodeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        //3.进行判断
        if (validateCode!=null && validateCodeInRedis != null && validateCode.equals(validateCodeInRedis)){
            //查找用户是否为会员
            Member member = memberService.findByTelephone(telephone);

            if (member == null){//非会员,自动注册会员

                member = new Member();
                member.setPhoneNumber(telephone);
                member.setRegTime(new Date());
                memberService.add(member);
            }
            //将成功登录的用户信息保存在Redis中-->实现多服务器数据共享
            //模拟JSESSIONID
            Cookie cookie = new Cookie("login_member_telephone", telephone);
            cookie.setPath("/");
            cookie.setMaxAge(60*60*24*30);//有效期
            response.addCookie(cookie);
            //模拟session
            String member_str = JSON.toJSON(member).toString();
            jedisPool.getResource().setex(telephone,5*60,member_str);
            return new Result(true,MessageConstant.LOGIN_SUCCESS);

        }else {//验证码输入错误

            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }

    }
}
